package controller

import (
	"fmt"
	"net/http"

	"example.com/m/demo14/models"
	"github.com/gin-gonic/gin"
)

type UserController struct{}

func (user UserController) GetUser(c *gin.Context) {
	//查询数据库
	/*  全部数据
	userList := []models.User{}
	models.DB.Find(&userList) */
	/*
	   指定条件
	*/
	userList := []models.User{}
	models.DB.Where("age>22").Find(&userList)
	c.JSON(http.StatusOK, gin.H{
		"code":   200,
		"result": userList,
	})
}

func (user UserController) CreateUser(c *gin.Context) {
	//创建数据
	newUser := models.User{
		Username: "小++",
		Age:      22,
		AddTime:  2222,
		Email:    "12123",
	}
	models.DB.Create(&newUser)
	fmt.Println(newUser)
	c.String(200, "创建用户成功")

}

func (user UserController) UpdateUser(c *gin.Context) {
	//修改id为1的用户的Username
	// models.DB.Model(&models.User{}).Where("id=?", 2).Update("username", "小++")
	// models.DB.First(&models.User{}, "username=?", "qq").Update("age", 55)
	//查询id为4的数据
	desuser := models.User{Id: 4}
	models.DB.Find(&desuser)
	fmt.Println(desuser)

	c.String(200, "修改用户成功")

}

func (user UserController) DeleteUser(c *gin.Context) {
	//删除所有Username为小++的用户
	// models.DB.Where("username=?", "小++").Delete(models.User{})
	models.DB.Delete(models.User{}, "username=?", "小++")
	//删除第一个Username为小++
	// models.DB.First(&models.User{}, "username=?", "小++").Delete(&models.User{})

	c.String(200, "删除用户成功")
}
